--[[

A pie chart display.

Shortcoming: only a subset of legends are shown, depending on window size, and there is no way to scroll.

--]]

local L = LibStub("AceLocale-3.0"):GetLocale("Skada", false)
local Skada = Skada

local mod = Skada:NewModule("PieDisplay")
local libwindow = LibStub("LibWindow-1.1")
local graph = LibStub("LibGraph-2.0")
local media = LibStub("LibSharedMedia-3.0")

-- Add to Skada's enormous list of display providers.
mod.name = "Pie display"
Skada.displays["pie"] = mod

function mod:HandlePieSelection(win, num)
	if num then
		--Skada:Print(win.db.name.." click on "..num)
	end
end

-- Called when a Skada window starts using this display provider.
function mod:Create(window)
	-- Skada "windows" are only logical windows. We need to create a frame.
	if not window.frame then
		window.colorcache = {} -- Persistent color cache
		window.frame = CreateFrame("Frame", window.db.name.."PieChartFrame", UIParent)
		window.frame.win = window -- Whee
		window.frame:SetMovable(true)
		window.frame:SetClampedToScreen(true)
		window.frame:SetWidth(window.db.width or 300)
		window.frame:SetHeight(window.db.height or 180)
		window.frame:SetBackdrop( {bgFile = media:Fetch("background", "Solid"), tile = false, edgeSize = 0, insets = {left = 0, right = 0, top = 0, bottom = 0} } )
		window.frame:SetBackdropColor(0, 0, 1, 0.2)
		window.frame:SetPoint("TOPLEFT", UIParent, "CENTER", 0, 0)
		window.frame:EnableMouse()
		window.frame:SetScript("OnMousedown", function(f, button) if button == "RightButton" then window:RightClick() end end)
		
		window.frame.legendframe = CreateFrame("Frame", nil, window.frame)
		window.frame.legendframe:SetWidth(140)
		window.frame.legendframe:SetPoint("TOPRIGHT", window.frame, "TOPRIGHT", 0, 0)
		window.frame.legendframe:SetPoint("BOTTOMRIGHT", window.frame, "BOTTOMRIGHT", 0, 0)
		window.frame.legendframe.AddLegend = Skada.AddLegend
		window.frame.legendframe.ClearLegends = Skada.ClearLegends
		window.frame.legendframe.ClickLegend = function(id, label, button) Skada.ClickRow(window.frame, window, id, label, button) end
		window.frame.legendframe.EnterLegend = function(id, label) Skada.EnterRow(window.frame, window, id, label) end
		window.frame.legendframe.LeaveLegend = function(id, label) Skada.LeaveRow(window.frame, window, id, label) end
		window.frame.legendframe.AdjustLegends = Skada.AdjustLegends
		Skada.SetupLegendScrolling(window.frame.legendframe)

		window.frame.MakeResizable = Skada.MakeResizable
		window.frame.OnResizingInProgress = function(self) window.chart:SetWidth(min(window.frame:GetWidth()-140, window.frame:GetHeight())); window.chart:SetHeight(min(window.frame:GetWidth()-140,window.frame:GetHeight())); window:UpdateDisplay(); window.frame.legendframe:AdjustLegends() end
		window.frame.OnResizingDone = function(self) window.db.width = window.frame:GetWidth(); window.db.height = window.frame:GetHeight() end
		window.frame:MakeResizable()
		window.frame:SetMinResize(140,40)
		
		-- Add a header.
		window.header = CreateFrame("Button", nil, window.frame)
		window.header:SetHeight(20)
		window.header:SetPoint("BOTTOMLEFT", window.frame, "TOPLEFT", 0, 0)
		window.header:SetPoint("BOTTOMRIGHT", window.frame, "TOPRIGHT", 0, 0)
		window.header:SetScript("OnMouseDown", function() window.frame:StartMoving() end)
		window.header:SetScript("OnMouseUp", function() window.frame:StopMovingOrSizing(); libwindow.SavePosition(window.frame) end)
		window.header:SetBackdrop( {bgFile = media:Fetch("statusbar", "Aluminium"), tile = false, edgeSize = 0, insets = {left = 0, right = 0, top = 0, bottom = 0} } )
		window.header:SetBackdropColor(0.1, 0.1, 0.3, 0.8)
		window.header:SetText(window.db.name)
		window.header:GetFontString():SetPoint("LEFT", window.header, "LEFT", 5, 1)
		window.header:GetFontString():SetJustifyH("LEFT")
		local myfont = CreateFont("MyTitleFont")
		myfont:SetFont(media:Fetch('font', "Accidental Presidency"), 12)
		window.header:SetNormalFontObject(myfont)		
		window.header.AddButton = Skada.AddButton
		window.header.AdjustButtons = Skada.AdjustButtons
		
		-- Add window buttons.
		window.header:AddButton(L["Configure"], "Interface\\Addons\\Skada\\images\\icon-config", "Interface\\Addons\\Skada\\images\\icon-config", function() Skada:OpenMenu(window) end)
		window.header:AddButton(L["Reset"], "Interface\\Addons\\Skada\\images\\icon-reset", "Interface\\Addons\\Skada\\images\\icon-reset", function() StaticPopup_Show("ResetSkadaDialog") end)
		window.header:AddButton(L["Segment"], "Interface\\Buttons\\UI-GuildButton-PublicNote-Up", "Interface\\Buttons\\UI-GuildButton-PublicNote-Up", function() Skada:SegmentMenu(window) end)
		window.header:AddButton(L["Mode"], "Interface\\Buttons\\UI-GuildButton-PublicNote-Up", "Interface\\Buttons\\UI-GuildButton-PublicNote-Up", function() Skada:ModeMenu(window) end)
		window.header:AddButton(L["Report"], "Interface\\Buttons\\UI-GuildButton-MOTD-Up", "Interface\\Buttons\\UI-GuildButton-MOTD-Up", function() Skada:OpenReportWindow(window) end)
		
		-- Add the actual graph. The pie chart does not function correctly unless width=height.
		local size = min(window.frame:GetWidth()-140, window.frame:GetHeight())
		local g=graph:CreateGraphPieChart("TestLineGraph",window.frame,"TOPLEFT","TOPLEFT",0,0,size,size)
		g:SetSelectionFunc(function(f, n) self:HandlePieSelection(window, n) end)
		window.chart = g
		
		--DEFAULT_CHAT_FRAME:AddMessage("Testing Line Graph")
	end
	window.frame:Show()
	
	-- Register with LibWindow-1.0.
	libwindow.RegisterConfig(window.frame, window.db)
	
	-- Restore window position.
	libwindow.RestorePosition(window.frame)
end

-- Called by Skada windows when the window is to be destroyed/cleared.
function mod:Destroy(win)
	wipe(win.colorcache)
	win.colorcache = nil
	win.frame.legendframe:ClearLegends()
	win.frame:Hide()
	win.frame = nil
	win.chart = nil
	win.header = nil
end

-- Called by Skada windows when title of window should change.
function mod:SetTitle(win, title)
	-- Set title.
	win.header:SetText(title)
end

local function round(num)
  local mult = 10^(0)
  return math.floor(num * mult + 0.5) / mult
end

-- Called by Skada windows when the display should be updated to match the dataset.
function mod:Update(win)
	-- Some modes may alter title continously.
	win.header:SetText(win.metadata.title)

	-- Find total value.
	local total = 0
	for i, data in ipairs(win.dataset) do
		if data.id then
			total = total + data.value
		end
	end
	
	win.chart:ResetPie()
	for i, data in ipairs(win.dataset) do
		if data.id and not data.ignore then	-- Total bar makes no sense for this display.
			local color
			if win.colorcache[data.id] then
				color = win.colorcache[data.id]
			else
				color = { math.random(), math.random(), math.random() }
				win.colorcache[data.id] = color
			end
			if data.value > 0 then
				--Skada:Print("adding "..data.label.." with "..((data.value / total) * 100))
				win.chart:AddPie(round((data.value / math.max(0.000001, total)) * 100),{color[1], color[2], color[3]})
			end
			
			win.frame.legendframe:AddLegend(data.id, data.label, color)
		end
	end
	win.frame.legendframe:AdjustLegends()
	win.chart:CompletePie({0.2,0.2,0.4})
end

-- Called by Skada windows when the window is to be completely cleared and prepared for new data.
function mod:Wipe(win)
	win.chart:ResetPie()
	win.frame.legendframe:ClearLegends()
end

function mod:Show(win)
	win.frame:Show()
end

function mod:Hide(win)
	win.frame:Hide()
end

function mod:IsShown(win)
	return win.frame:IsShown()
end

-- Called by Skada windows when window settings have changed.
function mod:ApplySettings(win)
	if win.db.barslocked then
		win.header:EnableMouse(false)
		win.frame.resizebutton:Hide()
	else
		win.header:EnableMouse(true)
		win.frame.resizebutton:Show()
	end
end

function mod:AddDisplayOptions(win, options)

end

